import { defineStore } from 'pinia';

// 定义农场游戏状态store
export const useFarmStore = defineStore('farm', {
  state: () => ({
    // 游戏资源
    gold: 100,
    water: 50,
    sun: 75,
    
    // 种子库存
    seeds: [
      { id: 1, name: '小麦', count: 5, icon: 'fas fa-wheat-awn', growthTime: 3000, value: 10 },
      { id: 2, name: '胡萝卜', count: 3, icon: 'fas fa-carrot', growthTime: 4500, value: 15 },
      { id: 3, name: '土豆', count: 2, icon: 'fas fa-seedling', growthTime: 6000, value: 20 }
    ],
    
    // 农场网格
    farmGrid: Array(9).fill().map(() => ({
      plant: null,
      stage: 0,
      watered: false,
      dead: false,
      plantedTime: 0
    })),
    
    // 背包物品
    backpack: [
      { id: 1, name: '小麦', count: 5, icon: 'fas fa-wheat-awn', growthTime: 3000, value: 10 },
      { id: 2, name: '胡萝卜', count: 3, icon: 'fas fa-carrot', growthTime: 4500, value: 15 },
      { id: 3, name: '土豆', count: 2, icon: 'fas fa-seedling', growthTime: 6000, value: 20 },
      { id: 4, name: '水壶', type: 'tools', count: 1, icon: 'fas fa-tint-slash', uses: 10 },
      { id: 5, name: '肥料', type: 'tools', count: 2, icon: 'fas fa-poo', uses: 5 }
    ],
    
    // 天气
    weather: '晴朗',
    
    // 设置
    settings: {
      music: true,
      soundEffects: true,
      autoSave: true
    },
    
    // UI状态
    currentView: 'farm',
    menuOpen: false,
    settingsOpen: false,
    filterType: 'all',
    
    // 通知
    notification: {
      show: false,
      message: ''
    }
  }),

  getters: {
    /**
     * 过滤背包物品
     * @returns {Array} 过滤后的背包物品
     */
    filteredItems(state) {
      if (state.filterType === 'all') return state.backpack;
      return state.backpack.filter(item => item.type === state.filterType);
    },
    
    /**
     * 获取植物图标
     * @param {Number} plantId - 植物ID
     * @returns {String} 图标类名
     */
    getPlantIcon: (state) => (plantId) => {
      const seed = state.seeds.find(s => s.id === plantId);
      return seed ? seed.icon : 'fas fa-seedling';
    }
  },

  actions: {
    /**
     * 初始化游戏
     */
    initGame() {
      this.gold = 100;
      this.water = 50;
      this.sun = 75;
      this.farmGrid = Array(9).fill().map(() => ({
        plant: null,
        stage: 0,
        watered: false,
        dead: false,
        plantedTime: 0
      }));
      this.weather = '晴朗';
      this.currentView = 'farm';
      this.menuOpen = false;
      this.settingsOpen = false;
      this.filterType = 'all';
      this.notification = {
        show: false,
        message: ''
      };
    },
    
    /**
     * 切换菜单
     */
    toggleMenu() {
      this.menuOpen = !this.menuOpen;
      if (this.menuOpen) this.settingsOpen = false;
    },
    
    /**
     * 切换设置
     */
    toggleSettings() {
      this.settingsOpen = !this.settingsOpen;
      if (this.settingsOpen) this.menuOpen = false;
    },
    
    /**
     * 显示通知
     * @param {String} message - 通知消息
     */
    showNotification(message) {
      this.notification.message = message;
      this.notification.show = true;
      
      // 3秒后自动隐藏
      setTimeout(() => {
        this.notification.show = false;
      }, 3000);
    },
    
    /**
     * 处理格子点击
     * @param {Number} index - 格子索引
     */
    handleCellClick(index) {
      const cell = this.farmGrid[index];
      if (cell.plant) {
        // 检查是否可以收获
        if (cell.stage >= 3) {
          this.harvestPlant(index);
        } else if (!cell.watered) {
          this.waterPlant(index);
        } else {
          this.showNotification('作物正在生长中...');
        }
      } else {
        // 种植作物
        this.plantSeed(index);
      }
    },
    
    /**
     * 种植种子
     * @param {Number} index - 格子索引
     */
    plantSeed(index) {
      // 简化版本：总是种植第一个可用的种子
      const seed = this.seeds.find(s => s.count > 0);
      if (!seed) {
        this.showNotification('没有可用的种子了！');
        return;
      }

      seed.count--;
      this.farmGrid[index] = {
        plant: seed.id,
        stage: 1,
        watered: true,
        dead: false,
        plantedTime: Date.now()
      };
      this.showNotification(`已种植 ${seed.name}`);
    },
    
    /**
     * 浇水
     * @param {Number} index - 格子索引
     */
    waterPlant(index) {
      if (this.water <= 0) {
        this.showNotification('没有水了！');
        return;
      }

      this.farmGrid[index].watered = true;
      this.water--;
      this.showNotification('已浇水');
    },
    
    /**
     * 收获植物
     * @param {Number} index - 格子索引
     */
    harvestPlant(index) {
      const cell = this.farmGrid[index];
      const seed = this.seeds.find(s => s.id === cell.plant);
      if (seed) {
        this.gold += seed.value;
        this.showNotification(`收获了 ${seed.name}，获得 ${seed.value} 金币`);
      }

      // 重置格子
      this.farmGrid[index] = {
        plant: null,
        stage: 0,
        watered: false,
        dead: false,
        plantedTime: 0
      };
    },
    
    /**
     * 购买物品
     * @param {Object} item - 物品对象
     */
    buyItem(item) {
      if (this.gold < item.price) {
        this.showNotification('金币不足！');
        return;
      }

      this.gold -= item.price;
      const existingItem = this.backpack.find(i => i.id === item.id);
      if (existingItem) {
        existingItem.count++;
      } else {
        this.backpack.push({...item, count: 1});
      }
      this.showNotification(`已购买 ${item.name}`);
    },
    
    /**
     * 使用物品
     * @param {Object} item - 物品对象
     */
    useItem(item) {
      this.showNotification(`使用了 ${item.name}`);
      // 在这里实现物品使用逻辑
      if (item.type === 'tools') {
        // 工具使用逻辑
        if (item.uses !== undefined) {
          item.uses--;
          if (item.uses <= 0) {
            // 移除用完的工具
            const itemIndex = this.backpack.findIndex(i => i.id === item.id);
            if (itemIndex !== -1 && this.backpack[itemIndex].count > 1) {
              this.backpack[itemIndex].count--;
            } else {
              this.backpack.splice(itemIndex, 1);
            }
          }
        }
      }
    },
    
    /**
     * 切换视图
     * @param {String} view - 视图名称
     */
    switchView(view) {
      this.currentView = view;
    },
    
    /**
     * 切换过滤类型
     * @param {String} type - 过滤类型
     */
    switchFilter(type) {
      this.filterType = type;
    },
    
    /**
     * 重置游戏
     */
    resetGame() {
      this.initGame();
    }
  }
});